﻿#include "msgwebview.h"
#include<QFile>
#include<QMessageBox>
#include<QJsonDocument>
#include<QJsonObject>
msgWebView::msgWebView(QWidget*parent):QWebEngineView(parent),m_channel(new QWebChannel(this))
{
    msgWebObj*obj1=new msgWebObj(this);
    msgWebObj*obj2=new msgWebObj(this);
    m_channel->registerObject("external0",obj1);//网络通道注册对象
    m_channel->registerObject("external_10001",obj2);
    page()->setWebChannel(m_channel);
    load(QUrl("qrc:/src/msgTmpl.html"));//初始化网页信息
}
msgWebView::~msgWebView(){

}
void msgWebView::appendMsg(QString msg, QString obj)
{
    QJsonObject jsonObj;
    jsonObj.insert("MSG",msg);
    QString ret=QJsonDocument(jsonObj).toJson(QJsonDocument::Compact);//紧凑模式
    if(obj==""){
        page()->runJavaScript(QString("appendHtml0(%1)").arg(ret));
    }else{
        page()->runJavaScript(QString("recvHtml_%1(%2)").arg(obj).arg(ret));
    }
}

msgWebObj::msgWebObj(QObject*parent):QObject(parent)
{
    initHtml();
}

void msgWebObj::initHtml()
{
    m_msgLeftTmpl=getHtml("msgleftTmpl");
    m_msgLeftTmpl.replace("%1","mde.jpg");
    m_msgRightTmpl=getHtml("msgrightTmpl");
    m_msgRightTmpl.replace("%1","msty.jpg");
}

QString msgWebObj::getHtml(QString html)
{
    QFile file(":/src/"+html+".html");
    if(file.open(QFile::ReadOnly)){
        QString ret=file.readAll();
        file.close();
        return ret;
    }else{
        QMessageBox::information(NULL,"info",QString::fromLocal8Bit("打开html文件失败!"));
        return "";
    }
}
